package com.azt.back.action.enquiry;

import com.azt.api.dto.PurchaseModel;
import com.azt.api.pojo.Admin;
import com.azt.api.pojo.Category;
import com.azt.api.pojo.TestEnquiryAI;
import com.azt.api.service.EnqEnquiryAnalysisService;
import com.azt.api.service.EnqEnquiryService;
import com.azt.api.service.ProCategoryService;
import com.azt.api.service.TestEnquiryService;
import com.azt.api.dto.EnqEnquiryItemForm;
import com.azt.back.util.ContextUtils;
import com.azt.back.util.Globals;
import com.azt.model.AjaxJson;
import com.azt.model.page.Pagination;
import com.azt.utils.RequestUtils;
import com.azt.utils.SessionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 询价单训练
 *
 * @author 张栋 2016年5月5日下午3:56:26
 */
@Controller
@RequestMapping("/enquiry")
@SessionAttributes(value = {"PModel"})
public class TestEnquiryAction {
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.setAutoGrowCollectionLimit(5000);
    }

    @Autowired
    private TestEnquiryService testEnquiryService;

//
//    @Autowired
//    private EnquiryOldService productService;

    @Autowired
    private ProCategoryService proCategoryService;

    @Autowired
    private EnqEnquiryService enqService;


    @Autowired
    private EnqEnquiryAnalysisService analysisService;


    @RequestMapping("/v_list.do")
    public String list(HttpServletRequest request, Integer pageNo, HttpServletResponse response, ModelMap model) {
        Map<String, String> searchMap = RequestUtils.getSearchMap(request);
        Pagination pagination = testEnquiryService.getTestEnquiryPage(pageNo == null ? 1 : pageNo, Globals.PAGE_SIZE, searchMap);
        model.put("pagination", pagination);
        return "purchase/test_enquiry_list";
    }

    /**
     * 预览
     *
     * @author 张栋  2016年6月15日上午11:01:47
     */
    @RequestMapping("/v_review.do")
    public void list(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        String string = RequestUtils.getString(request, "path");
        String excelToHtml = enqService.excelToHtml(string);
        PrintWriter writer = null;
        try {
            response.setCharacterEncoding("UTF-8");
            writer = response.getWriter();
            writer.write(excelToHtml);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();

        } finally {
            writer.close();
        }
    }


    /**
     * 更新url
     *
     * @author 张栋 2016年5月11日下午3:40:55
     */
    @RequestMapping("/o_excel_update.do")
    @ResponseBody
    public AjaxJson o_excel_update(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        AjaxJson j = new AjaxJson();
        String url = RequestUtils.getString(request, "url");
        Integer id = RequestUtils.getInteger(request, "id");
        TestEnquiryAI enquiry = testEnquiryService.getTestEnquiryById(id);
        enquiry.setExcelpath(url);
        testEnquiryService.updateTestEnquiry(enquiry);
        return j;
    }


    @RequestMapping("/mulity_retry.do")
    public String mulityRetry(HttpServletRequest request, ModelMap model) {
        Integer type = 1;
        try {
            Integer id = RequestUtils.getInteger(request, "id");
            type = RequestUtils.getInteger("type");

            TestEnquiryAI enquiry = testEnquiryService.getTestEnquiryById(id);
            // 解析
            Admin admin = ContextUtils.getAdmin();
            model.put("enquiry", enquiry);
            List<PurchaseModel> excelMulityWraps = analysisService.tryPurchaseMulity(enquiry.getExcelpath(), admin.getId(), type);
            if(excelMulityWraps.size() >1 ){
                //PModel 保存到session
                model.put("PModel",excelMulityWraps);

                model.put("wrapsize",excelMulityWraps.size());

                PurchaseModel tryPurchase = excelMulityWraps.get(0);
                List<String> titles = tryPurchase.getTitles();
                model.put("titles", titles);
                List<Integer> titleindex = tryPurchase.getTitleindex();
                model.put("titleindex", titleindex);
                //是否完美匹配
                model.put("titlePerfect", tryPurchase.isTitlePerfect());
                model.put("contentPerfect", tryPurchase.isContentPerfect());
                //最长列
                model.put("maxlength", tryPurchase.getMaxlength());
                model.put("contents",new ArrayList<>());


            }else if(excelMulityWraps.size()==1){
                readyModel(model, excelMulityWraps.get(0));
            }

            SessionUtils.broadcast("test", admin.getId(), "分析完毕");
        } catch (Exception e) {
                e.printStackTrace();
        }


        if (type == 1) {
            return "purchase/test_enquiryitem_mulity_model";
        } else {
            return "purchase/test_quoteitem_model";
        }
    }

    @RequestMapping("/mulity_one.do")
    public String mulityOne( ModelMap model,Integer index,Integer enqid,SessionStatus status){
        List<PurchaseModel> excelMulityWraps  = (List<PurchaseModel>) model.get("PModel");
        //清session
        if(index==excelMulityWraps.size()-1){
            status.setComplete();
        }
        model.put("mulityAnalysis",true);
        PurchaseModel purchaseModel  =excelMulityWraps.get(index);
        readyModel(model, purchaseModel);

        TestEnquiryAI enquiry = testEnquiryService.getTestEnquiryById(enqid);
        // 解析
        model.put("enquiry", enquiry);


        return "purchase/test_enquiryitem_model";
    }
    
    
    
    /**
     * 重新解析 excel
     *
     * @author 张栋 2016年5月9日下午7:19:40
     */
    @RequestMapping("/o_retry.do")
    public String o_save(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        Integer type = 1;
        try {
            Integer id = RequestUtils.getInteger(request, "id");

            type = RequestUtils.getInteger("type");

            TestEnquiryAI enquiry = testEnquiryService.getTestEnquiryById(id);
            // 解析
            Admin admin = ContextUtils.getAdmin();

            PurchaseModel tryPurchase = analysisService.tryPurchase(enquiry.getExcelpath(), admin.getId(), type);
            SessionUtils.broadcast("test", admin.getId(), "分析完毕");
            model.put("enquiry", enquiry);

            readyModel(model, tryPurchase);

        } catch (Exception e) {
            e.printStackTrace();
            model.put("msg", "解析失败");
        }

        if (type == 1) {
            return "purchase/test_enquiryitem_model";
        } else {
            return "purchase/test_quoteitem_model";
        }

    }

    private void readyModel(ModelMap model, PurchaseModel tryPurchase) {
        List<String> titles = tryPurchase.getTitles();
        model.put("titles", titles);
        List<Integer> titleindex = tryPurchase.getTitleindex();
        model.put("titleindex", titleindex);
        //是否完美匹配
        model.put("titlePerfect", tryPurchase.isTitlePerfect());
        //最长列
        model.put("maxlength", tryPurchase.getMaxlength());

        model.put("contents", tryPurchase.getContents());

        model.put("cellStats", tryPurchase.getCellStats());

        //没有被匹配的行
        model.put("nocontents", tryPurchase.getNocontents());

        model.put("contentPerfect", tryPurchase.isContentPerfect());

        model.put("shebeiindex", tryPurchase.getShebeiindex());

        model.put("md5secret", tryPurchase.getShebeiscret());

        //还要显示匹配到的系统的名称,这个麻烦,要查类别3的,并形成map
        Map<String, Category> categorysMap = proCategoryService.getCategorysMap();
        model.put("categorysMap", categorysMap);
    }

    /**
     * 保存item 详细列表
     *
     * @author 张栋 2016年5月17日下午2:44:23
     */
    @RequestMapping("/o_saveitem.do")
    @ResponseBody
    public AjaxJson o_saveitem(HttpServletRequest request, HttpServletResponse response,
                               @RequestBody EnqEnquiryItemForm item,
                               ModelMap model) {

        AjaxJson j = new AjaxJson();
        System.out.println(item.toString());
        String[] typenames = item.getTypenames();
        String[] oldtitles = item.getOldtitles();
        analysisService.saveOrUpdateRepository(item.getItem());
        analysisService.saveOrUpdateRepositoryTitles(typenames, oldtitles, item.getType());
        return j;
    }


    /**
     * 新增
     *
     * @author 张栋  2016年7月13日上午11:31:07
     */
    @RequestMapping("/o_add_test.do")
    @ResponseBody
    public AjaxJson o_add_test(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        AjaxJson j = new AjaxJson();
        String title = RequestUtils.getString(request, "title");
        TestEnquiryAI ai = new TestEnquiryAI();
        ai.setTitle(title);
        testEnquiryService.saveTestEnquiry(ai);
//        testEnquiryService.updateTestEnquiry(ai);
        return j;
    }

    /**
     * 删除
     *
     * @author 张栋  2016年7月13日上午11:31:16
     */
    @RequestMapping("/o_del_item.do")
    @ResponseBody
    public AjaxJson o_del_item(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        AjaxJson j = new AjaxJson();
        Integer id = RequestUtils.getInteger(request, "id");
        TestEnquiryAI enquiryById = testEnquiryService.getTestEnquiryById(id);
        testEnquiryService.deleteTestEnquiry(enquiryById);
        return j;
    }

    @RequestMapping("/o_save_item_stat.do")
    @ResponseBody
    public AjaxJson o_save_item_stat(HttpServletRequest request, HttpServletResponse response, ModelMap model, Integer id, Integer stat) {
        AjaxJson j = new AjaxJson();

        TestEnquiryAI enquiryById = testEnquiryService.getTestEnquiryById(id);
        enquiryById.setCanread(stat);
        testEnquiryService.updateTestEnquiry(enquiryById);

        return j;
    }

}
